package com.siyoumi.app.modules.app_book.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.annotation.RequestLimit;
import com.siyoumi.app.entity.*;
import com.siyoumi.app.modules.app_book.service.RequestLimitAppBook;
import com.siyoumi.app.modules.app_book.service.SvcBookOrder;
import com.siyoumi.app.modules.app_book.vo.VoBookOrderContinue;
import com.siyoumi.app.modules.app_book.vo.VoBookOrderEdit;
import com.siyoumi.app.modules.app_book.vo.VoBookSaleGetMoney;
import com.siyoumi.app.modules.user.service.SvcSaleSetting;
import com.siyoumi.app.modules.user.service.SvcSysCorpPay;
import com.siyoumi.app.modules.user.service.SvcSysSale;
import com.siyoumi.app.modules.user.vo.VoCorpPayResetStatus;
import com.siyoumi.app.modules.user.vo.VoSaleGetMoney;
import com.siyoumi.app.sys.entity.AesKi;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

//主播
@Slf4j
@RestController
@RequestMapping("/wxapp/app_book/api_sale")
public class ApiAppBookSale
        extends WxAppApiController {
    /**
     * 分销员信息
     */
    @GetMapping("/sale_info")
    public XReturn saleInfo() {
        SysSale entitySale = SvcSysSale.getBean().getEntitySaleByUid(getUid());
        XValidator.isNull(entitySale, "非主播");
        Map<String, Object> mapSale = XBean.toMap(entitySale, new String[]{
                "sale_id",
                "sale_level",
                "sale_type",
                "sale_uid",
                "sale_state",
                "sale_state_date",
                "sale_money_left",
                "sale_money_total",
        });
        //待入帐
        {
            JoinWrapperPlus<BookOrder> query = SvcBookOrder.getBean().listSaleQuery(InputData.getIns());
            query.eq("border_share_sales_uid", getUid())
                    .ge("border_status", 5) //已支付
                    .eq("border_handle", 0); //未入帐
            BigDecimal moneyFutrue = SvcBookOrder.getApp().sum(query, "border_share_sales_price");
            mapSale.put("money_futrue", moneyFutrue);
        }
        getR().put("sale", mapSale);
        getR().put("get_money_setting", SvcSaleSetting.getBean().getSettingTxt00()); //提现配置

        return getR();
    }

    /**
     * 提现
     */
    @PostMapping("/get_money")
    public XReturn getMoney(@Validated @RequestBody VoBookSaleGetMoney vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        //
        SysSale entitySale = SvcSysSale.getBean().getEntitySaleByUid(getUid());
        if (entitySale == null) {
            return XReturn.getR(20321, "用户没权限提现");
        }
        //
        VoSaleGetMoney voGetMoney = new VoSaleGetMoney();
        voGetMoney.setUid(getUid());
        voGetMoney.setApp_id("app_book");
        voGetMoney.setTrue_name(entitySale.getSale_name());
        voGetMoney.setMoney(vo.getMoney());
        return SvcSysSale.getBean().getMoney(voGetMoney);
    }

    /**
     * 支付
     */
    @GetMapping("/pay")
    public XReturn pay() {
        String orderId = input("order_id");
        XValidator.isNullOrEmpty(orderId, "miss order_id");

        SysAccsuperConfig config = XHttpContext.getXConfig();
        XReturn r = SvcSysCorpPay.getBean().pay(orderId);
        if (r.err()) {
            if (r.getErrMsg().contains("单号已超出重试期")) { //标记失败
                SysCorpPay entity = SvcSysCorpPay.getBean().getEntityByIdSrc(orderId);
                SysCorpPay entityUpdate = new SysCorpPay();
                entityUpdate.setCorppayq_status(10);
                entityUpdate.setCorppayq_status_date(XDate.now());
                entityUpdate.setCorppayq_return_str(r.toString());
                SvcSysCorpPay.getApp().saveOrUpdatePassEqualField(entity, entityUpdate);
            }
        }
        r.setData("app_id", config.getAconfig_pay_app_id());
        r.setData("mch_id", config.getAconfig_partnerId());

        return r;
    }

    /**
     * 支付检查
     */
    @GetMapping("/pay_check")
    public XReturn payCheck() {
        String orderId = input("order_id");
        XValidator.isNullOrEmpty(orderId, "miss order_id");

        return SvcSysCorpPay.getBean().payCheck(orderId);
    }

    /**
     * 分销员订单列表
     */
    @GetMapping("order_list")
    public XReturn orderList() {
        InputData inputData = InputData.fromRequest();

        String[] select = {
                "border_id",
                "border_date_begin",
                "border_date_end",
                "border_date_end_final",
                "border_create_date",
                "border_user_name",
                "border_user_phone",
                "border_day",
                "border_sku_user_count",
                "border_sku_user_count",
                "border_spu_count",
                "border_set_name",
                "border_set_day_price",
                "border_set_user_count",
                "border_price_spu",
                "border_deposit_price",
                "border_price_final",
                "border_deposit",
                "border_status",
                "border_share_sales_price",
                "border_share_sales_price_use",
                "border_handle",
                "border_handle_date",
                "border_continue",
                "border_continue_day_total",
                "border_spu_pay",
                "bspu_name",
                "bspu_logo",
                "bstore_title",
        };
        JoinWrapperPlus<BookOrder> query = SvcBookOrder.getBean().listSaleQuery(inputData);
        query.join(BookSpu.table(), BookSpu.tableKey(), "border_spu_id");
        query.join(BookStore.table(), BookStore.tableKey(), "border_store_id");
        query.eq("border_share_sales_uid", getUid());
        query.select(select);
        query.orderByDesc("border_create_date")
                .orderByAsc("border_id");

        IPage<BookOrder> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcBookOrder.getApp().getMaps(page, query);
        //
        AesKi aesKi = AesKi.ofByConfig();
        //
        List<Map<String, Object>> list = pageData.getRecords();
        for (Map<String, Object> item : list) {
            BookOrder entity = XBean.fromMap(item, BookOrder.class);
            item.put("border_user_name", XStr.markStar(entity.getBorder_user_name(), 1, 1));
            item.put("border_user_phone", XStr.markStarPhone(entity.getBorder_user_phone()));
            item.put("user_phone_enc", aesKi.encTxt(entity.getBorder_user_phone())); //加密

            item.put("border_date_end", entity.getBorder_date_end_final().plusDays(1)); //退房日期要+1
            item.put("end_date_continue", entity.endDate(true).plusDays(1));
        }

        getR().put("list", list);

        return getR();
    }

    /**
     * 修改订单
     *
     * @return
     */
    @RequestLimit(key = RequestLimitAppBook.class, second = 2)
    @PostMapping("order_edit")
    public XReturn orderEdit(@Validated @RequestBody VoBookOrderEdit vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        //
        BookOrder entityOrder = SvcBookOrder.getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");
        if (!entityOrder.getBorder_share_sales_uid().equals(getUid())) {
            return XReturn.getR(20197, "非主播订单，不能修改");
        }

        return SvcBookOrder.getBean().orderEdit(vo);
    }

    /**
     * 续单
     *
     * @param vo
     * @param result
     * @return
     */
    @RequestLimit(key = RequestLimitAppBook.class, second = 2)
    @PostMapping("order_continue")
    public XReturn orderContinue(@Validated @RequestBody VoBookOrderContinue vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        //
        BookOrder entityOrder = SvcBookOrder.getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");
        if (!entityOrder.getBorder_share_sales_uid().equals(getUid())) {
            return XReturn.getR(20197, "非主播订单，不能操作");
        }
        vo.setSale_uid(getUid());
        return SvcBookOrder.getBean().orderContinue(vo);
    }
}

